#!/bin/bash

export PATH=`defaults read $HOME/.MacOSX/environment PATH`
#export VERBOSE=1
#export REQUIRE_RTTI=1

svn=/opt/local/bin/svn

# CHECK SOURCE DIR
[ ! -d llvm ] && {
	
	REPOS_PREFIX="http://llvm.org/svn/llvm-project"
	
	# CLONE REPOSITORY
	$svn co $REPOS_PREFIX/llvm/trunk llvm \
		&& (
			cd llvm/tools \
				&& $svn co $REPOS_PREFIX/cfe/trunk clang
		) \
		&& (
			cd llvm/projects \
				&& $svn co $REPOS_PREFIX/compiler-rt/trunk compiler-rt
		) \
		|| echo "Failed to clone repository. Check network status." && exit
	
} || {
	
	# UPDATE REPOSITORY
	for dir in llvm llvm/tools/clang /llvm/projects/compiler-rt
	do
		( cd "$dir" && $svn update )
	done
	
}

# CHECK INTERNAL CLANG
[ -x /usr/local/bin/clang ] \
	&& export CC=/usr/local/bin/clang \
	&& export CXX=/usr/local/bin/clang++

# CHECK BUILD DIR
[ ! -d llvm-build ] \
	&& mkdir llvm-build

# BEGIN BUILD
cd llvm-build
../llvm/configure \
	--prefix=/usr/local \
	--disable-debug-runtime \
	--disable-profiling \
	--enable-debug-symbols \
	--enable-jit \
	--enable-libffi \
	--enable-optimized \
	--enable-pic \
	--enable-shared \
	--enable-targets=x86_64 \
		&& make `sysctl hw.ncpu | awk '{ print "-j" $2 + 1 }'` \
		&& make check-all \
		&& make install \
		&& echo done \
		|| echo failed

# END BUILD
cd ..
